<template>
  <div class="app-container" v-loading="loading">
    <div class="flex flex-wrap">
      <div class="flex justify-between w-full p-b-5">
        <div class="font-black text-xl"><!-- 大客户销售完成情况 --></div>
        <el-row :gutter="10" class="min-w-12/24" justify="end">
          <el-col :span="7">
            <el-date-picker
              style="width: 100%"
              v-model="queryParams.dateArr"
              type="daterange"
              range-separator="-"
              value-format="YYYY-MM-DD"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              @change="getData"
            />
          </el-col>
          <!-- <el-col :span="7">
            <el-tree-select
              class="w-full"
              :disabled="userStore.userInfo.orgId != 484"
              v-model="queryParams.deptIdArr"
              placeholder="请选择公司"
              default-expand-all
              multiple
              :data="companyOption"
              :props="{
                value: 'id',
                label: 'label',
                children: 'children'
              }"
              @change="getData"
            />
          </el-col> -->
          <!-- <el-col :span="7">
            <el-select
              class="w-full"
              v-model="queryParams.isTax"
              placeholder="是否含税"
              @change="getData"
            >
              <el-option
                v-for="item in yes_or_no"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              /> </el-select
          ></el-col> -->
          <el-col :span="3" class="text-right">
            <el-button icon="Download" @click="exportDetail">导出</el-button>
          </el-col>
        </el-row>
      </div>
      <div class="min-h-300px w-full">
        <el-table
          ref="levelTable"
          :data="tableData"
          style="width: 100%"
          border
          stripe
        >
          <el-table-column
            type="index"
            label="序号"
            align="center"
            width="60"
            fixed="left"
          />
          <!-- <el-table-column
            prop="deptName"
            label="地区"
            fixed="left"
            width="160"
          >
            <template #default="scope">
              <dict-drop
                :options="bidding_unit"
                :value="scope.row.deptId"
              ></dict-drop>
            </template>
          </el-table-column> -->
          <el-table-column
            v-for="(item, index) in tableLevel"
            :key="index"
            :prop="
              item.children && item.children.length ? undifined : item.prop
            "
            v-bind="item"
          >
            <template v-if="item.children && item.children.length">
              <el-table-column
                v-for="(item1, index1) in item.children"
                :key="index1"
                v-bind="item1"
              >
              </el-table-column>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getData"
        />
      </div>
    </div>
  </div>
</template>
<script setup name="CompletionTable">
import { reactive, toRefs, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { saleCompleteCondition } from '@/api/keyAccountSales/index'
import { strToArr, myToFixed } from '@/utils/commo'
import {
  companyOption //所属公司
} from '@/hooks/dict/order'
import FileSaver from 'file-saver'
import * as XLSX from 'xlsx'
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()
const {
  yes_or_no, //是否
  bidding_unit //内部单位
} = proxy.useDict('yes_or_no', 'bidding_unit')
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    dateArr: []
    // deptIdArr: [userStore.userInfo.orgId]
  },
  tableData: [],
  total: 0
})
let { queryParams, tableData, total } = toRefs(data)

const tableLevel = ref([
  {
    show: true,
    prop: 'customerName',
    label: '客户名称',
    align: 'center',
    minWidth: 130,
    showOverflowTooltip: true
  },
  {
    show: true,
    prop: 'proName',
    label: '签约项目',
    align: 'center',
    minWidth: 130,
    // formatter: row => {
    //   return proxy.selectDictLabel(bidding_unit.value, row.deptId)
    // },
    showOverflowTooltip: true
  },
  {
    show: true,
    prop: 'contractSum',
    label: '合同金额(元)',
    align: 'center',
    minWidth: 130,
    showOverflowTooltip: true
  },
  {
    show: true,
    prop: 'proSum',
    label: '项目成本(元)',
    align: 'center',
    minWidth: 130,
    showOverflowTooltip: true
  },
  {
    show: true,
    prop: 'sinTime',
    label: '签约日期',
    align: 'center',
    minWidth: 130,
    showOverflowTooltip: true
  },
  {
    show: true,
    prop: 'salesName',
    label: '销售人员',
    align: 'center',
    minWidth: 130,
    showOverflowTooltip: true
  },
  {
    show: true,
    prop: 'contractOrderNumber1',
    label: '客户联系人',
    align: 'center',
    showOverflowTooltip: true,
    children: [
      {
        show: true,
        prop: 'attnName',
        label: '姓名',
        align: 'center',
        width: 160,
        showOverflowTooltip: true
      },
      {
        show: true,
        prop: 'job',
        label: '职务',
        align: 'center',
        width: 160,
        showOverflowTooltip: true
      },
      {
        show: true,
        prop: 'attnPhone',
        label: '联系电话',
        align: 'center',
        width: 160,
        showOverflowTooltip: true
      }
    ]
  },
  {
    show: true,
    prop: 'remark',
    label: '备注',
    align: 'center',
    minWidth: 130,
    showOverflowTooltip: true
  }
])

const showColu = ref(true)
const loading = ref(false)
// 服务到期人数
function getData() {
  loading.value = true
  saleCompleteCondition(queryParams.value)
    .then(res => {
      tableData.value = res.rows
      loading.value = false
      total.value = res.total
    })
    .catch(() => {
      loading.value = false
    })
}
getData()

const getSummaries = param => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if (
      column.property == 'userName' ||
      column.property == 'deptName' ||
      column.property == 'transactionDeptName'
    ) {
      return ''
    }
    const values = data.map(item => {
      let property = strToArr(column.property, '.')
      return property.length > 1
        ? Number(item[property[0]][property[1]])
        : Number(item[column.property])
    })
    if (!values.every(value => isNaN(value))) {
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr)
        return prev + (isNaN(value) ? 0 : value)
      }, 0)
    } else {
      sums[index] = ''
    }
  })
  return sums
}
// 导出明细
const exportDetail = () => {
  proxy.downLoadByUrl(
    'ord/statistics/saleCompleteCondition/export',
    queryParams.value,
    '大客户销售完成情况.xlsx'
  )
}
// 前端导出excel
const exportExcel = excelName => {
  let tableBox = {
    completionTable: '服务到期人数分析',
    levelTable: '大客户销售完成情况',
    industryTable: '培训业务分类'
  }
  let tableRef = ''
  for (let key in tableBox) {
    console.log('导出key==>', key)
    if (tableBox[key] === excelName) {
      tableRef = key
    }
  }
  showColu.value = false
  setTimeout(() => {
    try {
      const $e = proxy.$refs[tableRef].$el
      let $table = $e.querySelector('.el-table__fixed')
      if (!$table) {
        $table = $e
      }

      const wb = XLSX.utils.table_to_book($table, { raw: true })
      const wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      })
      FileSaver.saveAs(
        new Blob([wbout], { type: 'application/octet-stream' }),
        `${excelName}.xlsx`
      )
      showColu.value = true
    } catch (e) {
      showColu.value = true
      if (typeof console !== 'undefined') console.error(e)
    }
  }, 500)
}
</script>
<style lang="scss" scoped>
.el-radio-group.groupBtn :deep(.el-radio__input) {
  display: none;
}
</style>
